/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.util;

import javax.servlet.http.HttpServletRequest;

public class ServletUtil {

	private HttpServletRequest request;
	public ServletUtil( HttpServletRequest request ) {
		this.request = request;
	}
			
	public String readString( String key, String defaultValue ) {
		try {
		  String str = request.getParameter(key);
		  //if (str!=null && str.length()>0) {
		    if (str.charAt(0)!=63) { // '?' is 63 indicating encoding failure
		      return request.getParameter(key);
		    } else {
		      return new String(request.getParameter(key).getBytes("ISO8859_1"), "UTF8");
		    }
		  //}
		} catch ( Exception e ) {}
		try {
			if ( request.getAttribute(key) != null ) { 
	    		return (String)request.getAttribute(key);
	    	}
			if ( request.getSession().getAttribute(key) != null ) { 
	    		return (String)request.getSession().getAttribute(key);
	    	}
		} catch ( Exception e ) {}
		return defaultValue;
	}
	
	public int readInt( String key, int defaultValue ) {
    	if ( request.getParameter(key) != null ) {
    		return Integer.parseInt( request.getParameter(key) );
    	}
    	try {
	    	if ( request.getAttribute(key) != null ) { 
	    		return Integer.parseInt( (String)request.getAttribute(key) );
	    	}
		  	if ( request.getSession().getAttribute(key) != null ) { 
	    		return (Integer)request.getSession().getAttribute(key);
	    	}
    	} catch ( Exception e ) {}
    	return defaultValue;
	}
	
	public boolean readBoolean( String key, boolean defaultValue ) {
		if ( request.getParameter(key) != null ) {
			return Boolean.parseBoolean( request.getParameter(key) );
		}
		try {
			if ( request.getAttribute(key) != null ) { 
				return Boolean.parseBoolean( (String)request.getAttribute(key) );
			}
			if ( request.getSession().getAttribute(key) != null ) { 
				return (Boolean)request.getSession().getAttribute(key);
			}
		} catch ( Exception e ) {}
		return defaultValue;
	}
	
	public String[] readStrings( String key, String[] defaultValue ) {
		try {
			String[] s = request.getParameterValues(key);
			return s!=null?s:defaultValue;
		} catch ( Exception e ) {
			return defaultValue;
		}
	}	
}
